package com.example.main;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

public class PubSubProducer {
    /**
     * 生产者 → 消息队列
     * 创建连接工厂,并设置参数
     * 创建连接 Connection
     * 创建通道 Channel
     * ----------------
     * 创建交换机
     * 创建队列
     * 交换机绑定到队列
     * <p>
     * 发送消息
     */
    //定义交换机名称
    private static final String FANOUT_EXCHANGE_NAME = "my_fanout_exchange";
    //定义一个短信队列
    private static final String SMS_QUEUE_NAME = "my_sms_queue";
    //定义一个邮件队列
    private static final String EMAIL_QUEUE_NAME = "my_email_queue";


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        if (true) {
            factory.setHost("127.0.0.1");
            factory.setPort(5672);
            factory.setUsername("guest");
            factory.setPassword("guest");
            factory.setVirtualHost("/");
        }
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //创建交换机
        /**
         * String exchange,             :交换机名称
         * BuiltinExchangeType type,    :绑定类型【 fanout 广播模式】【 direct 定向模式】【 topic 通配符】【 headers 首部交换】
         * boolean durable,             :是否持久化
         * boolean autoDelete,          :是否自动删除
         * boolean internal,            :是否内置,一般 false
         * Map<String, Object> arguments:参数
         */
        channel.exchangeDeclare(FANOUT_EXCHANGE_NAME, BuiltinExchangeType.FANOUT, true, false, false, null);
        //创建队列
        channel.queueDeclare(SMS_QUEUE_NAME, true, false, false, null);
        channel.queueDeclare(EMAIL_QUEUE_NAME, true, false, false, null);
        //交换机绑定队列
        /**
         * String queue                 :队列名称
         * String exchange              :交换机名称
         * String routingKey            :路由键,fanout 广播模式不需要路由键
         * Map<String, Object> arguments:参数
         */
        channel.queueBind(SMS_QUEUE_NAME, FANOUT_EXCHANGE_NAME, "", null);
        channel.queueBind(EMAIL_QUEUE_NAME, FANOUT_EXCHANGE_NAME, "", null);


        /**
         * String exchange      :交换机名称
         * String routingKey    :路由键
         * BasicProperties props:参数
         * byte[] body          :消息体
         */
        String str = null;
        for (int i = 0; i < 10; i++) {
            str = "Publish/Subscribe Fanout 模式 is so easy!" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            System.out.println("发送消息:\t" + str);
            channel.basicPublish(FANOUT_EXCHANGE_NAME, "", null, str.getBytes());
        }

        channel.close();
        connection.close();
        System.out.println("消息发送成功");
    }
}
